package com.fy.springmvc2.interrecptor;


import com.fy.springmvc2.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

public class MyInterceptor implements HandlerInterceptor {
    // preHandle是在处理器Handler执行之前执行的 返回true就是让请求继续执行，false:后续拦截器和处理器不执行了直接返回
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.err.println("preHandle执行...");

        // 登录权限验证的拦截
        // 从session中取出来登录的用户，判断用户是否登录过，然后决定是进行拦截或者放行
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        // 说明没有登录，拦截，返回到登录页面
        if (Objects.isNull(user)){
            request.setAttribute("error","网络故障!");
            //转发到登陆页面
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
        //如果登陆过 就放行
        request.getRequestDispatcher("welcome.jsp").forward(request,response);
        return true;
    }
}
